package com.shop.myweb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.myweb.common.R;
import com.shop.myweb.entity.Address;
import com.shop.myweb.entity.DTO.ShortAddress;
import com.shop.myweb.entity.DTO.UserDTO;
import com.shop.myweb.entity.User;
import com.shop.myweb.service.AddressService;
import com.shop.myweb.service.UserService;
import com.shop.myweb.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * @author: ZhuangShuo
 * @date: 2023/4/23 19:44
 * @description:
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user) {
        //1 页面提交的密码password
        String password = user.getPassword();

        //2 根据页面提交的用户民username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User userr = userService.getOne(queryWrapper);

        //3 如果没有查询到，则返回登录失败结果
        if (userr == null) {
            return R.error("登陆失败");
        }

        //4 密码比对，如果不一致则返回登录失败结果
        if (!userr.getPassword().equals(password)) {
            return R.error("密码错误");
        }


        //6 登陆成功，将用户ID存入Session并返回登陆成功结果
        request.getSession().setAttribute("user", userr.getId());
        return R.success(userr);
    }

    @PostMapping("/register")
    public R<User> register(HttpSession session, @RequestBody User user) {
        log.info("开始注册");
        if (user != null) {
            userService.save(user);
            session.setAttribute("user", user.getId());
            return R.success(user);
        } else
            return R.error("注册失败，请检查填写项目！");

    }

    @PostMapping("/add")
    public R<User> add(HttpSession session, @RequestBody User user) {
        log.info("新建用户");
        if (user != null) {
            userService.save(user);
            session.setAttribute("user", user.getId());
            return R.success(user);
        } else
            return R.error("注册失败，请检查填写项目！");

    }

    /**
     * 新增用户
     *
     * @return 返回R类型
     */
    @PostMapping("/save")
    public R<String> save(HttpServletRequest request, @RequestBody UserDTO userDTO) {
        User user = userDTO.getUser();

        if (user.getPhone().length() != 11)
            return R.error("手机号格式不正确，请重新填写");
        if (user.getPassword().length() < 6)
            return R.error("密码长度应大于6位，请重新填写");
        int page = userDTO.getPage();
        int pageSize = userDTO.getPageSize();
        userService.save(user);

        ShortAddress[] shortAddresses = userDTO.getAddresses();

        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "userPage_" + page + "_" + pageSize;
            redisTemplate.delete(key);
        }

        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != user.getId(), Address::getUserId, user.getId());

        addressService.remove(queryWrapper);

        for (ShortAddress shortAddress : shortAddresses) {
            Address address = new Address();
            address.setDetail(shortAddress.getValue());
            address.setConsignee(user.getUsername());
            address.setUserId(user.getId());
            address.setPhone(user.getPhone());
            address.setIsDeleted(0);
            addressService.save(address);
        }
        return R.success("新增用户成功");
    }


    /**
     * 用户信息的翻页查询
     *
     * @param page     当前多少页
     * @param pageSize 每页多少条
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {


        //构造分页构造器
        Page<User> pageInfo = new Page(page, pageSize);


        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "userPage_" + page + "_" + pageSize;
            if (redisTemplate.opsForValue().get(key) != null) {
                pageInfo = (Page<User>) redisTemplate.opsForValue().get(key);
                return R.success(pageInfo);
            }
            //构造条件构造器
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
            userService.page(pageInfo, queryWrapper);
            redisTemplate.opsForValue().set(key, pageInfo, 60, TimeUnit.SECONDS);
        } else {
            //条件构造器
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            //执行分页查询
            userService.page(pageInfo, queryWrapper);
        }
        return R.success(pageInfo);
    }


    /**
     * 根据id修改用户信息
     *
     * @return 返回R类型
     */
    @PutMapping("/edit")
    public R<String> update(@RequestBody UserDTO userDTO) {
        if (userDTO.getPage() != null && userDTO.getPageSize() != null) {
            int page = userDTO.getPage();
            int pageSize = userDTO.getPageSize();
            if (RedisUtils.isRedisAvailable(redisTemplate)) {
                String key = "userPage_" + page + "_" + pageSize;
                redisTemplate.delete(key);
            }
        }

        User user = userDTO.getUser();
        if (user.getPhone().length() != 11)
            return R.error("手机号格式不正确，请重新填写");
        if (user.getPassword().length() < 6)
            return R.error("密码长度应大于6位，请重新填写");

        ShortAddress[] shortAddresses = userDTO.getAddresses();


        userService.updateById(user);

        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != user.getId(), Address::getUserId, user.getId());

        addressService.remove(queryWrapper);

        for (ShortAddress shortAddress : shortAddresses) {
            Address address = new Address();
            address.setDetail(shortAddress.getValue());
            address.setConsignee(user.getUsername());
            address.setUserId(user.getId());
            address.setPhone(user.getPhone());
            address.setIsDeleted(0);
            addressService.save(address);
        }


        return R.success("用户信息修改成功");
    }

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Long id) {
        log.info("根据id查询用户信息...");
        User user = userService.getById(id);
        if (user != null) {
            return R.success(user);
        }
        return R.error("没有查询到相应的用户信息");
    }

    @DeleteMapping
    public R<String> delete(Long id, Integer page, Integer pageSize) {
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "userPage_" + page + "_" + pageSize;
            redisTemplate.delete(key);
        }
        userService.removeById(id);
        return R.success("删除成功");
    }

    @PutMapping("/status")
    public R<String> updateStatus(Long id, Integer page, Integer pageSize) {
        if (RedisUtils.isRedisAvailable(redisTemplate)) {
            String key = "userPage_" + page + "_" + pageSize;
            redisTemplate.delete(key);
        }
        User user = userService.getById(id);
        if (user.getStatus() == 1)
            user.setStatus(0);
        else
            user.setStatus(1);
        userService.updateById(user);
        return R.success("修改成功");
    }


//    @GetMapping("/getOneUser")
//    public R<User> getOneUser(String username) {
//        User user = userService.queryUser(username);
//        return R.success(user);
//    }

}
